<template>
	<div class="netteach-standard">
		<div class="netteach-crumbs">
		    <router-link to="/netteach">网络教研</router-link>
		    <span @click="goBack()"><i>></i>评课标准管理</span>
		     <span><i>></i>编辑</span>
		</div>

		<div class="standard-content">


			<div class="standard-new">
				<h3>评估标准修改</h3>

				<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
					<el-form-item label="标准名称" prop="name">
						<el-input v-model.trim="ruleForm.name" placeholder="最多可以输入20个字符"></el-input>
					</el-form-item>

					<el-form-item label="标准总分" prop="score" class='standard-score'>
						<el-input v-model="ruleForm.score" disabled></el-input>分
					</el-form-item>

                    <!-- 单级 -->
                    <template v-if="!isMulti">
                        <el-form-item label="科目" prop="subject">
                            <el-select v-model="ruleForm.subject"  placeholder="请选择科目">
                                <el-option 
                                    v-for="item in subjectList"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </template>
                    <!-- 多级 -->
                    <template v-else>
                        <el-form-item label="适用" prop="classify">
                            <el-select v-model="ruleForm.classify" placeholder="请选择分类">
                                <el-option
                                    v-for="item in classifyData"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </template>

					<el-form-item label="标准总分" prop="" class="total-score" required>
							<el-tabs v-model="tabTempIndex" type="card" editable @edit="handleTabsEdit">
								<el-tab-pane
									v-for="(item, index) in subAlbumData"
									:label="item.title"
									:name="item.name"
									:key="index" >

									<div class="total-score-list">
										<ul>
											<li v-for="(list,index2) in item.courseList" :key="index2">
												<div>
													<transition name="el-fade-in-linear">
														<el-form-item  :label="`评分标准`" label-width="100px"> 
															<el-input v-model.trim="list.name" placeholder="这是项目名称，20字符以内"  maxlength="20"></el-input>
														</el-form-item>
													</transition>
													<transition name="el-fade-in-linear"   v-if="list.children.length === 0">
														<el-form-item  label="设置分数" label-width="80px">
															<el-input-number v-model="list.score" controls-position="right" placeholder="设置分数" :min="0" :max="100"></el-input-number>
														</el-form-item>
													</transition>
												</div>
												<template  v-for="(node,index3) in list.children">
													<div :key="index3">
														<transition name="el-fade-in-linear">
															<el-form-item  :label="`评分项${index3+1}`" label-width="100px"> 
																<el-input type="textarea" :rows="4" v-model.trim="node.name" placeholder="这项目内容，200字符以内"  maxlength="200"></el-input>
															</el-form-item>
														</transition>
														<transition name="el-fade-in-linear">
															<el-form-item  label="设置分数" label-width="80px"> 
																<el-input-number v-model="node.score" controls-position="right" placeholder="设置分数" :min="0" :max="100"></el-input-number>
															</el-form-item>
														</transition>
														<i class="el-icon-close" @click="closeCourseList(index, index2, index3)"></i>
													</div>
												</template>
												<div class="catalog-list-btn buttonCSS">
													<el-button type="primary" style="width:100px;" @click="newCourseList(index, index2)">添加子评分项</el-button>
												</div>
											</li>
										</ul>
									</div>
									
								</el-tab-pane>
							</el-tabs>
					</el-form-item>
	
					<el-form-item>
						<el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
						<el-button type="primary" plain @click="resetForm('ruleForm')">取消</el-button>
					</el-form-item>
				</el-form>
			</div>
		</div>
	</div>
</template>

<script>
	
	export default {
		data(){
			return {
			
				ruleForm: {
					name: '',
					score: 0,
                    subject: '',
                    classify: ''
				},
				rules: {
					name: [
						{ required: true, message: '请输标准名称', trigger: 'blur' },
						{ min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
					],
					subject: [
						{ required: true, message: '请选择科目', trigger: 'change' }
                    ],
                    classify: [
						{ required: true, message: '请选择分类', trigger: 'change' }
					],
				},
				subAlbumData: [
					/*{
						title:  '项目',
						name: '1',
						courseList: [
							{	
								name: '',
								score: 0,
								children: [
									// {
									// 	content: '',
									// 	score: null
									// }
								]
								
							}
						]
					}*/
				],
				tabTempIndex: '1',
				subjectList: [],
				standardList: [],
                itemData: [],
                classifyData:[],
			}
		},

		created(){
            this.getStandardList()
            if(this.isMulti){//多级
			    this.getClassifyData();
            }else{
			    this.getSubjectList();
            }
        },
        computed: {
            isMulti(){
                return this.$store.getters.isMulti;
            }  
        },        
		methods: {
			/*
				请求评分标准列表
			*/
			getStandardList(){
				let success = (res=>{
	
					for (let i = 0; i <  res.data.standard_item.length; i++) {
						this.subAlbumData.push({
							title:  `评分标准${i+1}`,
							name: `${i+1}`,
							courseList: [] 
						});

						this.subAlbumData[i].courseList.push({
							name:  res.data.standard_item[i].name,
							score: res.data.standard_item[i].score,
							children: res.data.standard_item[i].child
						})
					}
					this.ruleForm.name = res.data.name;
					this.ruleForm.score = res.data.total_score;
					this.ruleForm.subject = res.data.subject_id;
					this.ruleForm.classify = res.data.classify_id;

					// console.info(this.subAlbumData)
				});

				this.$ajax({
					url: 'api/network/standard_detail',
					methos: 'get',
					params: {id: this.$route.query.id},
					func: {success: success}
				})
			},
			goBack(){
				this.$router.back(-1)
			},
			/*
			    请求科目
			*/
			getSubjectList(){
			    let success = (res=>{
			        this.subjectList = res.data;
			        // this.subjectList.unshift({'id': 0, 'name': '所以科目'})
			    });

			    this.$ajax({
			        url: 'api/cate/subject',
			        method: 'get',
			        params: {},
			        func: {success: success}
			    })
            },
            /*
			    多级：获取分类
			*/
			getClassifyData(){
			    let success = (res=>{
			        this.classifyData = res.data;
			    });

			    this.$ajax({
			        url: 'api/network/eva_standard_classify',
			        method: 'get',
			        params: {},
			        func: {success: success}
			    })
            },
			/*
				计算评分标准总分 & 提取提交的健值
			*/
			totalStandards(){
				this.ruleForm.score = 0
				let arr = []
				for (let i = 0; i < this.subAlbumData.length; i++) {
					if (this.subAlbumData[i].courseList) {
						for (let j = 0; j < this.subAlbumData[i].courseList.length; j++) {

							if (this.subAlbumData[i].courseList[j].name === '' || this.subAlbumData[i].courseList[j].score === '') {
								this.$message.error(`标准总分的项目${i+1}--项目名称${i+1} 或 分数不能为空`)
								return
							}
							if (this.subAlbumData[i].courseList[j].children.length !== 0) {
								this.subAlbumData[i].courseList[j].score = 0
							}
							this.ruleForm.score += parseInt(this.subAlbumData[i].courseList[j].score);
							if (this.subAlbumData[i].courseList[j].children) {
								for (let k = 0; k < this.subAlbumData[i].courseList[j].children.length; k++) {

									if (this.subAlbumData[i].courseList[j].children[k].name === '' || this.subAlbumData[i].courseList[j].children[k].score === '') {
										this.$message.error(`标准总分的项目${i+1}--项目内容${i+1}--${j+1} 或 分数不能为空`)
										return
									}

									this.ruleForm.score += parseInt(this.subAlbumData[i].courseList[j].children[k].score)
								}
								
							}
							arr.push(this.subAlbumData[i].courseList[j])
						}
					}
						
				};

				this.ruleForm.arr = arr;
			},
			/*重新组建提交的数据方式*/
			setSubAlbumData(){

				for (let i = 0; i < this.subAlbumData.length; i++) {
					if (i === 0) {
						this.itemData.push({});
					}
					
					for (let j = 0; j < this.subAlbumData[i].courseList.length; j++) {

						this.itemData.push({
							name: this.subAlbumData[i].courseList[j].name,
							pid: 0,
							score: this.subAlbumData[i].courseList[j].score
						});
					}
				};

				for (let i = 0; i < this.subAlbumData.length; i++) {
					
					for (let j = 0; j < this.subAlbumData[i].courseList.length; j++) {

						if (this.subAlbumData[i].courseList[j].children.length !== 0) {
							for (let k = 0; k < this.subAlbumData[i].courseList[j].children.length; k++) {
								this.itemData.push({
									name: this.subAlbumData[i].courseList[j].children[k].name,
									pid: i+1,
									score: this.subAlbumData[i].courseList[j].children[k].score
								});
							}
						}
					}
				};
			},
			/*
				数据提交
			*/
			submitForm(formName) {

				this.totalStandards()
				this.$refs[formName].validate((valid) => {
					if (valid) {
						this.setSubAlbumData()
						let success = (res=>{
							this.itemData = []
							this.$message.success(res.msg);
							this.$router.back(-1)
						});

						let fail = (res =>{
							this.$message.error(res.msg)
						})

						let params = {
							id: this.$route.query.id,
							name: this.ruleForm.name,
							total_score: this.ruleForm.score,
							item_data: this.itemData,
							authority: 1,
							status: 1,
                            userid: this.$g.user_id,
                            subject_id:!this.isMulti?this.ruleForm.subject:null,//单级
                            classify_id:this.isMulti?this.ruleForm.classify:null,//多级
						};

						this.$ajax.put('api/network/eva_standard', params, {func:{success: success, fail: fail}})
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			},
			resetForm(formName) {
				// this.$refs[formName].resetFields();
				this.$router.back(-1)
			},
			/*
				标准总分增删减
				
			*/
			handleTabsEdit(targetName, action) {
			
				if (action === 'add') {
					let newTabIndex = this.subAlbumData.length + 1;
			
					this.tabTempIndex = (newTabIndex).toString();
					
					this.subAlbumData.push({
						title:  `评分标准${newTabIndex}`,
						name: (newTabIndex).toString(),
						score: '',
						courseList: [
							{	
								name: '',
								score: 0,
								children: [
									// {
									// 	content: '',
									// 	score: ''
									// }
								]
								
							}
						]
					})
				}
			
				if (action === 'remove') {

					if (this.subAlbumData.length ===1) { 
						this.$message.error('项目不能为空');
						return 
					}
					var tabs = deep_clone( this.subAlbumData );
					var newtabs =  [];
					var continue_ornot = false;
					var ivn = 0;
					
					for (var i = 0; i <  tabs.length; i++) {

						if( parseInt(tabs[i].name) === parseInt(targetName)){
								
							continue_ornot = true;
							if( parseInt( this.tabTempIndex ) > 1 && i === parseInt( this.tabTempIndex ) ){

								this.tabTempIndex = (parseInt( this.tabTempIndex )).toString()
								// console.info(this.tabTempIndex ,1)
			
							}else if( parseInt( this.tabTempIndex ) > i ){
								this.tabTempIndex = (parseInt( this.tabTempIndex) -1).toString()
									// console.info(this.tabTempIndex ,2)
							}
							continue;
						}else{
							ivn = ivn+1;
							if( continue_ornot ){
								tabs[i].title = `项目-${ivn}`;
								tabs[i].name = (ivn).toString();
							}
							newtabs.push( tabs[i] );
						}
					}
				
					this.subAlbumData = deep_clone( newtabs );
				}
			},
			newCourseList(index, index2){

				this.subAlbumData[index].courseList[index2].children.push({
					content: '',
					score: ''
				})
			},
			/*
				
			 */
			closeCourseList(index, index2, index3){
				// console.info(index, index2, index3)
				this.subAlbumData[index].courseList[index2].children.splice(index3, 1)
			}
		}
	}
</script>